package edu.njupt.ssm.service;

import edu.njupt.ssm.bean.Product;
import edu.njupt.ssm.dao.ProductDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Title: ProductServiceImpl
 * @Author:孙尊义
 * @version:1.0
 * @since:1.0
 * @Date 2024/11/5 13:35
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao dao;

    @Autowired
    private RedisTemplate<Object,Object> rt;

    @Override
    public Double findTurnover() {

        //获取Redis指定key的操作对象
        BoundValueOperations<Object, Object> ops = rt.boundValueOps("turnover");
        //从缓存中获取指定key的value
        Object turnover = ops.get();
        //若缓存中没有该数据，则先从DB中查询，然后在写入缓存
        //使用双重检测锁机制来预防缓存击穿
        if (turnover == null) {
            synchronized (this) {
                turnover = ops.get();
                if (turnover == null) {
                    //获取当前日期，并且格式化
                    Date now = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(now);
                    turnover = dao.selectTurnover(format);

                    //将查询结果写入缓存
                    ops.set(turnover, 10, TimeUnit.SECONDS);
                }
            }
        }
        return (Double) turnover;
    }

    @Override
    @Cacheable(value = "pc",key = "'product_all'")
    public List<Product> findAllProducts() {

        return dao.selectAllProducts();
    }

    @Override
    @Cacheable(value = "pc",key = "'product_'+#name")
    public List<Product> findProductsByName(String name) {
        return dao.selectProductsByName(name);
    }

    @Override
    @CacheEvict(value = "pc",allEntries = true)
    public void addProduct(Product product) {
        dao.insertProduct(product);
    }
}
